package cn.jetpiece.cloud.joss.api.basic.utils;

import cn.hutool.core.util.StrUtil;
import cn.jetpiece.cloud.feign.instance.FeignInstance;
import cn.jetpiece.cloud.joss.api.object.JossObjectFeign;
import cn.jetpiece.cloud.joss.api.object.model.params.GetObject;
import cn.jetpiece.cloud.joss.api.object.model.result.UploadObjectResult;
import cn.jetpiece.cloud.model.util.SpringContextHolder;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

/**
 * 上传工具类
 *
 * @author XuJZ
 */
@Slf4j
public class JossUploadUtils {

    /**
     * 把字符串中的/掐头去尾
     *
     * @param str 字符串
     * @return 去掉头尾中的/的结果
     */
    public static String breakOffBothEnds(String str) {
        if (str.startsWith("/")) {
            str = str.substring(1);
        }
        if (str.endsWith("/")) {
            str = str.substring(0, str.length() - 1);
        }
        return str;
    }

    /**
     * 格式化路径，去除头尾的/,第一个不为空取掉一个，为空向后取
     *
     * @param paths 待格式化数组
     * @return 格式化后path字符串
     */
    public static String formatPath(String... paths) {
        for (String path : paths) {
            if (StrUtil.isNotBlank(path)) {
                path = breakOffBothEnds(path);
            }
            if (StrUtil.isNotBlank(path)) {
                return path;
            }
        }
        return null;
    }

    /**
     * 将格式化后的路径加入到列表
     *
     * @param pathList 路径列表
     * @param paths    待加入路径数组
     */
    public static void formatPathJoin(List<String> pathList, String... paths) {
        for (String path : paths) {
            if (StrUtil.isBlank(path)) {
                continue;
            }
            path = breakOffBothEnds(path);
            if (StrUtil.isNotBlank(path)) {
                pathList.add(path);
            }
        }
    }

    /**
     * 获取jossToken
     * @param preSign 预签名
     * @param preExpires 签名实现
     * @param path 路径
     * @return jossToken
     */
    public static String getJossToken(String preSign, Long preExpires, String path) {
        if (preSign == null) {
            return null;
        }
        GetObject obj = new GetObject();
        obj.setPreSign(preSign);
        obj.setPreExpires(preExpires);
        UploadObjectResult uploadObjectResult = getJossFeignToken().getObject(path, obj);
        return uploadObjectResult.getJossToken();
    }

    /**
     * 获取JossObjectFeign
     * @return JossObjectFeign
     */
    public static JossObjectFeign getJossFeignToken() {
        JossObjectFeign jossObjectApi = null;
        try {
            jossObjectApi = SpringContextHolder.getBean(JossObjectFeign.class);
        } catch (Exception e) {
            log.error("Not Local Joss ConfigApi Bean!");
        }
        if (jossObjectApi == null) {
            jossObjectApi = FeignInstance.getInstance().newInstance(JossObjectFeign.class, "jetpiece-joss");
        }
        return jossObjectApi;
    }
}
